package com.showtao.front.controller;

import java.io.IOException;
import java.util.Calendar;

import org.apache.commons.io.FilenameUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.showtao.front.service.ResourceService;
import com.showtao.front.service.UploadedFileHandler;

@Controller
public class UploadController {

	private Logger logger = LoggerFactory.getLogger(UploadController.class);

	@Autowired
	private ResourceService resourceService;
	@Autowired
	private UploadedFileHandler uploadedFileHandler;

	@RequiresPermissions (value={"resource_upload"})
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public @ResponseBody String upload(
			@RequestParam MultipartFile file, Model model) throws IOException {
		logger.info("*** start process upload ***");
		String resId = uploadedFileHandler.putTemp(
				file.getInputStream(),
				FilenameUtils.getBaseName(file.getOriginalFilename())
						+ Calendar.getInstance().getTimeInMillis() + "."
						+ FilenameUtils.getExtension(file.getOriginalFilename()));
		logger.info("uploaded file transferred to temp folder with uri : " + resId);
		return resId;
	}

}
